#!/usr/bin/python

from pysqlite2 import dbapi2 as sqlite3
import os
import sys
import xmpp
import time

class JSender:
	""" class for xmpp messages sending """

	connection = 0;
	cursor     = 0;
	path_app   = ''
	receivers  = []
	sleep_secs = 60*5
	jid        = 0
	jcl        = 0
	# jabber account name and password
	# don't forget to specify
	acc_name   = ''
	acc_pass   = ''

	def __init__(self):
		""" constructor """
		# set paths
		self.path_app = os.path.dirname(os.path.abspath(sys.argv[0]))
		
		# set connect
		self.connection = sqlite3.connect(self.path_app + '/jsender.sqlite')
		self.cursor = self.connection.cursor()

		# get receivers list
		self.cursor.execute('select jid from receivers where active = 1')
		for row in self.cursor.fetchall():
			self.receivers.append(row[0]);

	def loop(self):
		# processing
		while True:
			try:
				if not self.jcl:
					# xmpp init
					self.jid = xmpp.protocol.JID(self.acc_name)
					self.jcl = xmpp.Client(self.jid.getDomain(), debug=[])
					self.jcl.connect()
					self.jcl.auth(self.jid.getNode(), self.acc_pass)
					print 'authentication finished'
				
				self.jcl.sendPresence()
			except:
				print 'connection failed!'
				self.jid = 0
				self.jcl = 0

			# get awaiting messages
			try:
				self.cursor.execute('select * from messages where time_sent = 0')
				for row in self.cursor.fetchall():
					#print row
					reclist = []
					if row[1] != '*':
						reclist = row[1].split(',')
					else:
						reclist = self.receivers
					for email in reclist:
						try:
							self.jcl.send(xmpp.protocol.Message(email, row[2]))
						except:
							print 'message sending failed!'
							self.jid = 0
							self.jcl = 0

					sql = "update messages set time_sent = %i where id = %i" % (time.time(), row[0])
					self.cursor.execute(sql)
					self.connection.commit()
			except:
				print 'was not able to get new messages from database!'

			time.sleep(self.sleep_secs)


js = JSender()
js.loop()
